<template>
  <div class="question-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 头部按钮 -->
        <div class="btn_wrapper">
          <span style="font-size: 12px; color: pink"
            >说明：目前支持学科和关键字条件筛选</span
          >
          <el-button
            type="success"
            size="small"
            icon="el-icon-edit"
            @click="$router.push('/questions/new')"
            >新增试题</el-button
          >
        </div>

        <!-- 筛选表单 -->
        <el-form
          :model="requestParameters"
          ref="requestParameters"
          label-width="80px"
        >
          <div class="filter-container">
            <el-row>
              <el-col :span="6">
                <el-form-item label="学科">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.subjectID"
                    placeholder="请选择"
                    @change="handleSubject"
                  >
                    <el-option
                      v-for="item in subjectList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="二级目录">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.catalogID"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in twoLevelDirectoryList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标签">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.tags"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in tagsList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关键字">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.keyword"
                    placeholder="根据题干搜索"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="试题类型">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.questionType"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in questionType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="难度">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.difficulty"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in difficulty"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="方向">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.direction"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in direction"
                      :key="item.value"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="录入人">
                  <el-select
                    style="width: 100%"
                    v-model="requestParameters.creatorID"
                    placeholder="请选择"
                  >
                    <el-option
                    v-for="item in EntryUserList"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="题目备注">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.remarks"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="企业简称">
                  <el-input
                    style="width: 100%"
                    v-model="requestParameters.shortName"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="城市">
                  <el-col :span="12">
                    <el-select
                      class="filter-item"
                      style="width: 100%"
                      v-model="requestParameters.province"
                      placeholder="请选择"
                      @keyup.enter="handleFilter"
                      @change="handleProvince"
                      filterable
                    >
                      <el-option
                        v-for="(item,index) in province"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="12">
                    <el-select
                      class="filter-item"
                      style="width: 100%"
                      v-model="requestParameters.city"
                      placeholder="请选择"
                      @keyup.enter="handleFilter"
                      filterable
                    >
                      <el-option
                        v-for="(item,index) in cityData"
                        :key="index"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-col>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item style="text-align: right">
                  <el-button size="small" @click="resetForm">清除</el-button>
                  <el-button size="small" type="primary" @click="handleFilter"
                    >搜索</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>

        <!-- 数据记录 -->
        <el-alert
          v-if="alertText !== ''"
          :title="alertText"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>

        <!-- 表格 -->
        <el-table
          :data="questionsList"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="试题编号" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学科">
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column label="目录">
            <template slot-scope="scope">
              <span>{{ scope.row.catalog }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="questionType"
            label="题型"
            :formatter="formatQuestionType"
          ></el-table-column>
          <el-table-column label="题干" width="280">
            <template slot-scope="scope">
              <span v-html="scope.row.question"></span>
            </template>
          </el-table-column>
          <el-table-column label="录入时间" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | parseTimeByString }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="difficulty"
            label="难度"
            :formatter="formatDifficulty"
          ></el-table-column>
          <el-table-column prop="creator" label="录入人">
            <template slot-scope="scope">
              <span>{{ scope.row.creator }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template v-slot="scope">
              <el-button
                title="预览"
                size="small"
                type="primary"
                icon="el-icon-view"
                circle
                plain
                @click="handlePreview(scope.row.id)"
              ></el-button>
              <el-button
                title="修改"
                size="small"
                type="success"
                icon="el-icon-edit"
                circle
                plain
                @click="$router.push({
                  path: '/questions/new',
                  query:{'id':scope.row.id}
                })"
              ></el-button>
              <el-button
                title="删除"
                size="small"
                type="danger"
                icon="el-icon-delete"
                circle
                plain
                 @click="handleDelete(scope.row.id)"
              ></el-button>
              <el-button
                title="加入精选"
                size="small"
                type="warning"
                icon="el-icon-check"
                circle
                plain
                @click="handleChoiceAdd(scope.row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <div class="pages">
            <el-pagination
              background
              style="margin-top: 20px; text-align: right"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[2, 5, 10, 20, 50]"
              :page-size="pagesize"
              layout="prev, pager, next, sizes, jumper"
              :total="counts"
            >
            </el-pagination>
          </div>
        </div>

        <!-- 查看的弹出层 -->
        <el-dialog title="题目预览" :visible.sync="dialogVisible" width="40%" @close="isShow=false">
          <div class="title">
            <el-row>
              <el-col :span="6">【题型】：{{formatQuestionType('', '', questionsDetailObj.questionType, '')}}</el-col>
              <el-col :span="6">【编号】：{{questionsDetailObj.id}}</el-col>
              <el-col :span="6">【难度】：{{formatDifficulty('', '', questionsDetailObj.difficulty, '')}}</el-col>
              <el-col :span="6">【标签】：{{questionsDetailObj.tags}}</el-col>
              <el-col :span="6">【学科】：{{questionsDetailObj.subjectName}}</el-col>
              <el-col :span="6">【目录】：{{questionsDetailObj.directoryName}}</el-col>
              <el-col :span="6">【方向】：{{questionsDetailObj.direction}}</el-col>
            </el-row>
          </div>
          <el-divider></el-divider>
          <div class="info">
            【题干】：
            <div style="color: blue"><p v-html="questionsDetailObj.question"></p></div>
            <div style="padding-bottom: 5px">
              {{formatQuestionType('', '', questionsDetailObj.questionType, '')}} 选项：（以下选中的选项为正确答案）
            </div>
            <!-- 单选 -->
            <div v-if="questionsDetailObj.questionType === '1'">
              <el-radio-group :value="radio">
                <el-radio :label="item.isRight" style="display: block" v-for="item in questionsDetailObj.options" :key="item.id">{{item.title}}</el-radio>
              </el-radio-group>
            </div>
            <!-- 多选 -->
            <div v-if="questionsDetailObj.questionType === '2'">
              <el-checkbox-group :value="checkboxList">
                <el-checkbox :label="item.isRight" style="display: block" v-for="item in questionsDetailObj.options" :key="item.id">{{item.title}}</el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 简答题 -->
            <div v-if="questionsDetailObj.questionType === '3'">
              <span v-html="questionsDetailObj.question"></span>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="answer">
            【参考答案】：<el-button type="danger" size="small" @click="isShow=true">视频答案预览</el-button>
            <br>
            <video v-if="isShow" :src="questionsDetailObj.videoURL" controls style="width:100%"></video>
            <!-- <video v-if="isShow" src="http://vjs.zencdn.net/v/oceans.mp4" controls style="width:100%"></video> -->
          </div>
          <el-divider></el-divider>
          <div class="analysis">
            【答案解析】：<span v-html="questionsDetailObj.answer"></span>
          </div>
          <el-divider></el-divider>
          <div class="remarks">
            【题目备注】：{{questionsDetailObj.remarks}}
          </div>

          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as subjectSimple } from '@/api/hmmm/subjects'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as entryUser } from '@/api/base/users'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import {
  list as questionsList,
  detail as questionsDetail,
  remove as questionsRemove,
  choiceAdd as questionsChoiceAdd
} from '@/api/hmmm/questions'

export default {
  data () {
    return {
      requestParameters: {
      },

      subjectList: [], // 学科列表
      twoLevelDirectoryList: [], // 二级目录列表
      tagsList: [], // 标签列表

      province: [],
      cityData: [],

      EntryUserList: [], // 录入人渲染列表
      questionType, // 试题类型列表
      difficulty, // 难度列表
      direction, // 方向列表

      questionsList: [], // 题库列表
      alertText: '',

      page: 1,
      pagesize: 5,
      counts: 0,

      listLoading: true,
      dialogVisible: false,
      radio: 1, // 单选框
      checkboxList: [1], // 多选框
      questionsDetailObj: {},
      isShow: false,
      selectedParameters: { }
    }
  },
  created () {
    this.getSubjectList() // 获取学科简单列表
    this.getCityData() // 获取城市列表
    this.getEntryUser() // 获取录入人
    this.getQuestionsList() // 获取题库列表
  },
  methods: {
    // 获取学科简单列表
    async getSubjectList () {
      const res = await subjectSimple()
      // console.log(res)
      this.subjectList = res.data
    },
    // 选学科获取到二级目录,标签
    handleSubject (subjectID) {
      this.getDirectoryList(subjectID)
      this.gettagsList(subjectID)
      // 清空 目录和标签
      this.twoLevelDirectoryList = ''
      this.tagsList = ''
    },
    // 获取目录详情列表
    async getDirectoryList (id) {
      const res = await directorysSimple({ subjectID: id })
      // console.log(res)
      this.twoLevelDirectoryList = res.data
    },
    // 获取标签列表
    async gettagsList (id) {
      const res = await tagsSimple({ subjectID: id })
      // console.log(res)
      this.tagsList = res.data
    },
    // 获取省
    getCityData () {
      this.province = provinces()
    },
    // 选省获取到市
    handleProvince (e) {
      this.cityData = citys(e)
    },
    // 页面一加载获取录入人
    async getEntryUser () {
      const { data: res } = await entryUser()
      // console.log(res)
      this.EntryUserList = res
    },

    // 获取题库列表
    async getQuestionsList () {
      this.listLoading = true
      const { data: res } = await questionsList({ pagesize: this.pagesize, page: this.page })
      // console.log(res)
      this.questionsList = res.items // 获取数据
      this.counts = res.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
      this.listLoading = false
    },
    // 格式化题型
    formatQuestionType (row, column, cellValue, index) {
      const res = questionType.find((item) => item.value === +cellValue)
      return res ? res.label : '未知'
    },
    // 格式化难度
    formatDifficulty (row, column, cellValue, index) {
      const res = difficulty.find((item) => item.value === +cellValue)
      return res ? res.label : '未知'
    },

    // 清除
    resetForm () {
      this.requestParameters = {}
      this.getQuestionsList()
    },
    // 搜索
    async handleFilter () {
      this.page = 1
      this.selectedParameters = { ...this.requestParameters }
      const { data } = await questionsList({
        ...this.selectedParameters,
        page: this.page,
        pagesize: this.pagesize
      })
      this.questionsList = data.items
      this.counts = data.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
    },

    // 分页
    async handleSizeChange (newSize) {
      // console.log(`每页 ${newSize} 条`)
      this.pagesize = newSize
      this.page = 1
      const { data: res } = await questionsList({
        ...this.selectedParameters,
        pagesize: this.pagesize,
        page: this.page
      })
      // console.log(res)
      this.questionsList = res.items // 获取数据
      this.counts = res.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
    },
    async handleCurrentChange (newPage) {
      // console.log(`当前页: ${newPage}`)
      this.page = newPage
      const { data: res } = await questionsList({
        ...this.selectedParameters,
        pagesize: this.pagesize,
        page: this.page
      })
      // console.log(res)
      this.questionsList = res.items // 获取数据
      this.counts = res.counts // 获取总条数
      this.alertText = `共 ${this.counts} 条记录`
    },

    // 预览
    async handlePreview (id) {
      this.dialogVisible = true
      const res = await questionsDetail({ id })
      // console.log(res)
      this.questionsDetailObj = res.data
    },
    // 删除
    async handleDelete (id) {
      try {
        await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示')
        await questionsRemove({ id })
        this.$message.success('删除成功!')
        // 判断该页面是不是只有一条数据 并且 页码不是第一页
        if (this.questionsList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getQuestionsList()
      } catch (err) {
        return err
      }
    },
    // 加入精选
    async handleChoiceAdd (id) {
      try {
        await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示')
        await questionsChoiceAdd({ id, choiceState: 1 })
        this.$message.success('加入精选成功!')
        // 判断该页面是不是只有一条数据 并且 页码不是第一页
        if (this.questionsList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getQuestionsList()
        this.$router.push({ path: '/questions/choice' })
      } catch (err) {
        return err
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.question-container {
  margin: 10px 0;
  padding: 0 10px;

  .btn_wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .alert {
    margin: 10px 0px;
  }

  .pagination {
    margin-top: 10px;
  }
}

::v-deep .el-form-item--medium .el-form-item__content{
  line-height: 40px;
}
</style>
